﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Windows.Forms;
using System.IO;
using ELS.User;

namespace ELS.BackupRestore
{
    class BackupRestoreController
    {
        BackupRestoreDataAccess bkDataAccess = new BackupRestoreDataAccess();
        internal DataTable GetListFileData()
        {
            return bkDataAccess.SelectAllFile();            
        }

        internal int AddNewFile()
        {
            int rowInsert = 0;
            string currentFileName = UserCommon.fileBackUpPath + "ELS_" + DateTime.Now.Ticks+".sql";
            bkDataAccess.CreateBackUpFile(currentFileName);
            if (File.Exists(currentFileName))
            {
                FileInfo info = new FileInfo(currentFileName);
                FileStream fileStream = File.OpenRead(info.FullName);
                BinaryReader reader = new BinaryReader(fileStream);
                long numBytes = new FileInfo(info.FullName).Length;
                byte[] buffer = reader.ReadBytes((int)numBytes);

                string fileName = info.Name.Replace(info.Extension, "");
                int fileSize = int.Parse(info.Length.ToString());
                string fileType = info.Extension.Replace(".", "");
                rowInsert += bkDataAccess.InsertNewFile(fileName, buffer, fileSize, fileType);
                // Delete temporary backup file
                reader.Close();
                fileStream.Close();

                File.Delete(currentFileName);
            }
            //string script = bkDataAccess.ScriptDatabase();
            return rowInsert;
        }

        internal List<string> GetAllTableName()
        {
            DataTable dtTables = new DataTable();            
            dtTables = bkDataAccess.SelectAllTableName();

            List<string> listTableName = new List<string>();
            string name = "";
            for (int i = 0; i < dtTables.Rows.Count; i++)
            {
                name = dtTables.Rows[i][0].ToString();
                if (name == "Group")
                {
                    name = "[Group]";
                }
                if (name == "User")
                {
                    name = "[User]";
                }
                listTableName.Add(name);
            }
            return listTableName;                 
        }

        internal bool DeleteBackUpFile(List<string> list)
        {
            int rowDelete = 0;
            for (int i = 0; i < list.Count; i++)
            {
                rowDelete += bkDataAccess.DeleteBackUpFile(list[i]);
            }
            return rowDelete > 0;
        }

        internal bool RestoreDb(int currentFileId)
        {
            int success = -1;            
            success = bkDataAccess.RestoreDb(currentFileId);
            return success > 0;
        }
    }
}
